package aes;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
import java.util.Base64;

/**
 * @author changfu.he
 * @date 2022/3/8
 */
public class AESUtils3 {
    private static String secretKey = "boooooooooom!!!!";
    private static String iv = "123456789abcdefg";

    static {
        // 追加 bcprov-jdk15on 的jar 依赖
        Security.addProvider(new BouncyCastleProvider());
    }

    public static Cipher initCipher(int model) throws Exception {
        byte[] keyBytes = secretKey.getBytes();
        byte[] ivKeyBytes = iv.getBytes();

        String algorithm = "AES";
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, algorithm);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(ivKeyBytes);
        String cipherAlgorithm ="AES/CBC/PKCS7Padding";

        Cipher cipher=Cipher.getInstance(cipherAlgorithm,"BC") ;
        cipher.init(model, secretKeySpec, ivParameterSpec);
        return cipher;
    }

    public static String encrypt(String plaintext) throws Exception {
        // 加密模式
        Cipher cipher=initCipher(Cipher.ENCRYPT_MODE);
        byte[] bytes = cipher.doFinal(plaintext.getBytes("UTF-8"));
        String s = java.util.Base64.getEncoder().encodeToString(bytes);
        System.out.println(s);
        return s;
    }

    public static String decrypt(String ciphertext)throws Exception {
        // 解密模式
        Cipher cipher=initCipher(Cipher.DECRYPT_MODE);
        String s = new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)));
        System.out.println(s);
        return s;

    }

    public static void main(String[] args) throws Exception {
//        encrypt("www.csdn.net");
        decrypt("HJXO2zLOCqVcxyuI9c2+Rg==");
    }
}
